<?php
//funkciya udaleniya fayla
function deletfile($directory,$filename)
{
  // открываем директорию (получаем дескриптор директории)
  $dir = opendir($directory);
  
  // считываем содержание директории
while(($file = readdir($dir)))
{
          // Если это файл и он равен удаляемому ...
  if((is_file("$directory/$file")) && ("$directory/$file" == "$directory/$filename"))
  {
    // ...удаляем его.
    unlink("$directory/$file");
                  
     // Если файла нет по запрошенному пути, возвращаем TRUE - значит файл удалён.
    if(!file_exists($directory."/".$filename))
    {
        return true;   
    }
  }
}
  // Закрываем дескриптор директории.
  closedir($dir);
}

//vivodim libo randomno 9 saytov s luboy kategorii, libo vse s konkretnoy
function get_sites($id_category = false)
{
    if($id_category)
    {
        $id_category = check_id($id_category);
        
        $query = "SELECT s.id_site, s.site_url, s.description, s.screenshot, s.count, c.name
                  FROM {$dbPrefix}sc__sites AS s
                  JOIN {$dbPrefix}sc__categorys AS c ON s.id_category = c.id_category
                  WHERE s.id_category = $id_category ORDER BY id_site DESC";
    }
    else
    {
        $query = "SELECT * FROM {$dbPrefix}sc__sites ORDER BY RAND() LIMIT 9";
    }

	$result = mysql_query($query);

	if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$sites = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
 		$sites[] = $row;
 	}
         
 	return $sites;
}

// poluchaem konkretniy sayt dlyta redaktirovaniya
function get_cpecific($id)
{
    $id = check_id($id);    
    
    $tmp = "SELECT id_site, site_url, description, id_category, screenshot
              FROM {$dbPrefix}sc__sites
              WHERE id_site = '%d'";
    $query = sprintf($tmp, $id);
    $result = mysql_query($query);
    
    if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$site = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
 		$site[] = $row;
 	}
         
 	return $site;
    
}
// sohranyaem noviy sayt
function save_site($site_url, $description, $category)
{
    if($site_url == '' || $description == '' || $category == '')
    {
        header("Location: index.php?add");
        exit; 
    }
    else
    {
        preg_match('/(?:[^:]*:\/\/)?(?:www)?\.?([^\/]+\.[^\/]+.*)/i',$site_url,$match);
        $cut_url = $match[1];
        
        $site_url = check_string($cut_url);
        $description = check_string($description);
        $category = check_id($category);
        
        if(isset($_FILES['screen']) && file_exists($_FILES['screen']['tmp_name']))
        {        
            $tmp = "INSERT INTO {$dbPrefix}sc__sites (site_url, description, id_category)VALUES ('%s', '%s', '%d')";
            $query = sprintf($tmp, $site_url, $description, $category);
            mysql_query($query);
            
            $id = mysql_insert_id();
            $tmp = "UPDATE {$dbPrefix}sc__sites SET screenshot = '%s'
                                                WHERE id_site = '%d'";
            $query = sprintf($tmp, $id, $id);        
            
            //poluchayu fail i zamenyayu ego imya na id
            $path = 'img/';
            $old_name = $_FILES['screen']['name'];
            $name = "$id.jpg";
            $old_name = $name;
            $path = $path.$old_name;
            
            $temp_path = $_FILES['screen']['tmp_name'];
            
            copy($temp_path, $path);
        }
        else
        {
            $tmp = "INSERT INTO {$dbPrefix}sc__sites (site_url, description, id_category)VALUES ('%s', '%s', '%d')";
            $query = sprintf($tmp, $site_url, $description, $category);        
        }
        
        $result = mysql_query($query);
        if (!$result)
    		die(mysql_error());
            
        
        return mysql_affected_rows();
        
        header("Location: index.php");
        exit;       
    }    
}

//sohranyaem dannie posle redaktirovaniya sayta
function update_data($id_site, $site_url, $description, $category)
{
    if($site_url == '' || $description == '' || $category == '')
    {
        header("Location: index.php?id=$id_site");
        exit; 
    }
    else
    {
        preg_match('/(?:[^:]*:\/\/)?(?:www)?\.?([^\/]+\.[^\/]+.*)/i',$site_url,$match);
        $cut_url = $match[1];
        
        $id_site = check_id($id_site);
        $site_url = check_string($cut_url);
        $description = check_string($description);
        $category = check_id($category);
        //proveryayu esli bil zagrujen noviy screenshot ili net i vipolnyayu zapros
        if(isset($_FILES['screen']) && file_exists($_FILES['screen']['tmp_name']))
        {
            //poluchayu fail i zamenyayu ego imya na id
            $path = 'img/';
            $old_name = $_FILES['screen']['name'];
            $name = "$id_site.jpg";
            $old_name = $name;
            $path = $path.$old_name;
            
            $temp_path = $_FILES['screen']['tmp_name'];
            
            copy($temp_path, $path);
            
            $tmp = "UPDATE {$dbPrefix}sc__sites SET site_url = '%s',                                            
                                                    description = '%s',
                                                    id_category = '%d',
                                                    screenshot = '%s'
                                                WHERE id_site = '%d'";
            $query = sprintf($tmp, $site_url, $description, $category, rtrim($old_name, ".jpg"), $id_site);
        }
        else
        {
            $tmp = "UPDATE {$dbPrefix}sc__sites SET site_url = '%s',                                            
                                                    description = '%s',
                                                    id_category = '%d'
                                                WHERE id_site = '%d'";
            $query = sprintf($tmp, $site_url, $description, $category, $id_site);
        }
        
        
        $result = mysql_query($query);
        if (!$result)
    		die(mysql_error());
            
        return mysql_affected_rows();
    }
        
}

//udalyaem screenshot
function delete_img($num_of_screen)
{
    $num_of_screen = check_id($num_of_screen);
    $path = "img";
    $name = "$num_of_screen.jpg";
    $del_file = deletfile($path, $name);
    if($del_file)
    {
        $tmp = "UPDATE {$dbPrefix}sc__sites SET screenshot = NULL WHERE id_site = '%d'";
        $query = sprintf($tmp, $num_of_screen);
        $result = mysql_query($query);
    
    	if (!$result)
    		die(mysql_error());

    }
}

//udalyaem sayt
function delete_data($id, $site_url)
{    
    $id = check_id($id);
    $site_url = check_string($site_url);
    delete_img($id);    
    
    $tmp = "DELETE FROM {$dbPrefix}sc__sites WHERE id_site = '%d'";
    $query = sprintf($tmp, $id);
    $result = mysql_query($query);

	if (!$result)
		die(mysql_error());
    header("Location: index.php?note=$site_url");
    exit;
}

//poluchaem menu cherez bazu
function get_menu()
{    
    $query = "SELECT * FROM {$dbPrefix}sc__categorys ORDER BY id_category";
    
    $result = mysql_query($query);

	if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$categorys = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
        $categorys[$row['id_category']] = $row;
 	}
        
 	return $categorys;   
}

//schotchik perehoda po ssilkam
function counter($id, $site_url)
{
    $id = check_id($id);
    $site_url = check_string($site_url);
    
    $tmp = "UPDATE {$dbPrefix}sc__sites SET count = count + 1 WHERE id_site = '%d'";
    $query = sprintf($tmp, $id);
    $result = mysql_query($query);
    
    if (!$result)
		die(mysql_error());
    header("Location: http://$site_url");
    exit;
}

function get_last_sites($iLimit = 3) {
	$query = "SELECT * FROM {$dbPrefix}sc__sites ORDER BY id_site DESC LIMIT {$iLimit}";
	$result = mysql_query($query);
	$rows = array();
	if ($result)
		while ($row = mysql_fetch_assoc($result))
			$rows[] = $row;

	return $rows;
}